<template>
  <div class="app-container">
    <div class="filter-container">
    <el-button type="primary" @click="handleCreate">话题编辑</el-button>
    <el-button type="danger" @click="del">删除</el-button>
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" border fit highlight-current-row
      style="width: 100%;min-height:1000px;"
       @selection-change="handleSelectionChange"
      >
         <el-table-column
        type="selection"
        width="52">
         </el-table-column>
      <el-table-column align="center" label="id" width="80">
        <template slot-scope="scope">

              <span >{{scope.row.forum_id}}</span>
         
        </template>
      </el-table-column>
      <!-- <el-table-column width="100px" align="center"  label="名称">
        <template slot-scope="scope">
          <span>{{scope.row.username}}</span>
        </template>
      </el-table-column> -->
      <el-table-column min-width="100px" label="用户id" >
        <template slot-scope="scope">
          <span >{{scope.row.user_id}}</span>
          
        </template>
      </el-table-column>
     <el-table-column min-width="100px" label="标题">
        <template slot-scope="scope">
          <span >{{scope.row.title}}</span>
          
        </template>
      </el-table-column>
        <el-table-column min-width="100px" label="状态">
        <template slot-scope="scope">
          <span >{{scope.row.status}}</span>
           
        </template>
        </el-table-column>
      <el-table-column align="center" label="操作" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
      
          <el-button v-if="scope.row.status!='deleted'" size="mini" type="primary" @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button v-if="scope.row.status!='deleted'" size="mini" type="primary" @click="handleUpdate(scope.row)">详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

<!--添加用户s-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
     <quillEditor></quillEditor>
    </el-dialog>
    
<!--添加用户e-->

    <el-dialog title="Reading statistics" :visible.sync="dialogPvVisible">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel"> </el-table-column>
        <el-table-column prop="pv" label="Pv"> </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">确定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
import { getALList, addmsg, editMsg, delMsg } from '@/api/topic/TopicM'
import waves from '@/directive/waves' // 水波纹指令
import { parseTime } from '@/utils'
import { asy_gets } from '@/utils/async_script_cb.js'
const log = console.log
const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

import { quillEditor } from 'vue-quill-editor'

// require styles
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// arr to obj ,such as { CN : "China", US : "USA" }
// const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
//   acc[cur.key] = cur.display_name
//   return acc
// }, {})

export default {
  name: 'complexTable',
  directives: {
    waves
  },
  data() {
    return {
      isUse_list: [{
        name: '是',
        val: 1
      },
      {
        name: '否',
        val: 0
      }
      ],
      type_L: [
        {
          name: '普通文章',
          id: 101
        },
        {
          name: '公告文章',
          id: 201
        }, {
          name: '新闻公告',
          id: 301
        }

      ],
      radio: '1',
      new_temp: {
        email: '',
        password: '',
        roleIdList: '',
        status: '',
        username: '',
        role: ''
      },
      temp: {
        email: undefined,
        password: '',
        roleIdList: '',
        username: '',
        status: '1'
      },
      all_role: null,
      multipleSelection: '',
      tableKey: 0,
      list: [],
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' }
      ],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [
          { required: true, message: '请输入类型名称', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入email', trigger: 'blur', type: 'email' }
        ],
        roleIdList: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        username: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        isUse: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        timestamp: [
          {
            type: 'date',
            required: true,
            message: 'timestamp is required',
            trigger: 'change'
          }
        ],
        title: [
          { required: true, message: 'title is required', trigger: 'blur' }
        ]
      },
      downloadLoading: false
    }
  },
  components: {
    quillEditor: quillEditor
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  async created() {
    const result = await asy_gets('https://webapi.amap.com/maps?v=1.4.8&key=8e7630bc79aa7f10e129c9effd1f5839')
    this.getList()
  },
  methods: {
    edit() {

    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    del: function() {
      const userId = []
      this.multipleSelection.forEach((val, index, x) => {
        userId.push(this.multipleSelection[index].artmanId)
      })
      this.$confirm(`确定删除？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((e) => {
        console.log(userId)
        delMsg(userId).then((e) => {
          if (e.data.code === 500) {
            this.$message({
              message: e.data.msg,
              type: 'warning'
            })
          } else {
            this.$notify({
              title: '成功',
              message: '操作成功',
              type: 'success',
              duration: 1000,
              onClose: () => {
                this.getList()
              }
            })
          }
        }).catch((e) => {
          console.log(e)
        })
      }).catch((e) => {
        console.log(e)
      })
    },
    created_user: function(data) {
      this.listLoading = true
      this.$refs.dataForm.validate(valid => {
        this.listLoading = false
        console.log('creatd_user')
        console.log(this.temp)
        const temp = {
          name: this.temp.name,
          status: this.temp.status,
          type: this.temp.type
        }
        addmsg(temp).then((e) => {
          if (e.data.code === 500) {
            this.$message(e.data.msg)
          } else {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '操作成功',
              type: 'success',
              duration: 1200,
              onClose: () => {
                this.getList()
              }
            })
          }
        }).catch((e) => {
          console.log(e)
          this.resetTemp()
          this.$message(e)
        })
      })
    },
    getList() {
      this.listLoading = true
      // 获取所有用户信息
      // 获取所有用户信息
      const temp_data = {
        limit: this.listQuery.limit,
        page: this.listQuery.page
      }
      getALList(temp_data)
        .then(res => {
          console.log('res_____')
          console.log(res)
          this.listLoading = false
          this.list = res.data.page.list
          this.total = res.data.page.totalPage
        })
        .catch(err => {
          this.listLoading = false
          log(err)
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {
        status: '1',
        artmanId: '',
        isUse: false
      }
    },
    get_allROle() {
      return new Promise((resolve, reject) => {
        getAllRole()
          .then((e) => {
            resolve(e)
          }).catch((e) => {
            reject(e)
          })
      })
    },
    handleCreate() {
      this.$router.push({ path: '/TopicM/detailTopic', query: { usermsg: '' }})
      // this.$nextTick(() => {
      //   this.resetTemp()
      //   this.dialogStatus = 'create'
      //   this.dialogFormVisible = true
      //   this.$refs['dataForm'].clearValidate()
      // })
    },
    handleUpdate(row) {
      console.log('rew_______________')
      console.log(row)
      this.temp = row
      this.$nextTick(() => {
        // this.resetTemp()
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$refs['dataForm'].clearValidate()
        this.getList()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.temp.roleIdList = [this.temp.roleIdList]
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          editMsg(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 1200,
              onClose: () => {
                this.getList()
              }
            })
          })
        }
      }).catch((e) => {
        console.log(e)
      })
    },
    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      // const index = this.list.indexOf(row)
      // this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = [
          'timestamp',
          'title',
          'type',
          'importance',
          'status'
        ]
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    }
  }
}
</script>
